/*
 * ItemRoutingValueResource.cpp
 *
 *  Created on: 2014. 3. 4.
 *      Author: mega
 */

#include <algorithm>
#include <Toolkit/Str.h>
#include <Database/Static.h>
#include "ItemRoutingValueResource.h"

#include "../macro.h"

namespace ProjectZ { namespace NResource {

ItemRoutingValueResource::ItemRoutingValueResource()
{

}

ItemRoutingValueResource::~ItemRoutingValueResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](ITEMROUTINGVALUETREE::value_type & pair) {
		delete pair.second;
	} );
}

void
ItemRoutingValueResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](ITEMROUTINGVALUETREE::value_type & pair) {
		delete pair.second;
	} );
	clsFlyTree.clear();
}

bool
ItemRoutingValueResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_item_routing_value");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Toolkit::Str<30> DESC;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_IDX >> pFly->_QUALITY1 >> pFly->_QUALITY2 >> pFly->_QUALITY3
				>> pFly->_QUALITY4 >> pFly->_QUALITY5 >> pFly->_QUALITY6 >> pFly->_QUALITY7
				>> pFly->_QUALITY8 >> pFly->_QUALITY9 >> pFly->_QUALITY10
				>> pFly->_EFFECT_MIN >> pFly->_EFFECT_MAX >> DESC;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_IDX] = pFly;
	}

	return true;
}

ItemRoutingValueResource::Flyweight *
ItemRoutingValueResource::GetFly(int idx)
{
	auto iter = clsFlyTree.find(idx);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}


} /*NResource*/ } /*ProjectZ*/
